import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Treebeard} from 'react-treebeard';
import _ from 'lodash';

export default class TreeBlock extends Component {
  static propTypes = {
    data: PropTypes.any,
  }

  state = {
    cursor: null,
    nodes: TreeBlock.createTreeNode(this.props.data || {}),
  }

  onToggle = (node, toggled) => {
      if (this.state.cursor) {
        this.state.cursor.active = false;
      }
      node.active = true;
      if (node.children) {
        node.toggled = toggled;
      }
      this.setState({ cursor: node });
  }

  static createTreeNode(data, key) {
    let title = null;
    if (_.isArray(data)) {
      title = `${key || 'array'} [${_.size(data)}]`;
    } else if (_.isObject(data)) {
      title = `${key || 'object'} {${_.size(data)}}`;
    } else {
      title = `${key || typeof data}: ${data}`;
    }
    let node = {
      name: title,
      toggled: true,
      children: [],
    };
    if (_.isObject(data)) {
      _.forEach(data, function(value, key) {
        if (_.isObject(value)) {
          node.children.push(TreeBlock.createTreeNode(value, key));
        } else {
          node.children.push({name: `${key}: ${value}`});
        }
      });
    }
    return node;
  }

  componentWillReceiveProps(nextProps) {
    this.setState({nodes: TreeBlock.createTreeNode(nextProps.data || {})});
  }

  render() {
    return <div style={{maxHeight: '600px', overflow: 'auto'}}>
      <Treebeard data={this.state.nodes} onToggle={this.onToggle} />
    </div>;
  }
}
